<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
        <el-form-item label="是否线上展示" prop="onlineFlag">
          <el-select 
            v-if="sysYesNo.length > 0"
            v-model="queryParams.onlineFlag"
            placeholder="请选择是否线上展示"
            clearable
            filterable
            style="width: 180px"
            @change="handleOnlineFlagChange">
            <el-option v-for="d in sysYesNo" :key="d.value" :label="d.label" :value="d.value" />
          </el-select>
          <el-select v-else v-model="queryParams.onlineFlag" placeholder="加载中..." disabled style="width: 180px" />
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-select 
            v-if="goodsStatusOptions.length > 0"
            v-model="queryParams.status"
            placeholder="请选择商品状态"
            clearable
            filterable
            style="width: 180px"
            @change="handleStatusChange">
            <el-option v-for="s in goodsStatusOptions" :key="s.value" :label="s.label" :value="s.value" />
          </el-select>
          <el-select v-else v-model="queryParams.status" placeholder="加载中..." disabled style="width: 180px" />
        </el-form-item>
      <el-form-item label="排序序号" prop="sortNo">
        <el-input
          v-model="queryParams.sortNo"
          placeholder="请输入排序序号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否线上展示" prop="onlineFlag">
        <el-select 
          v-if="sysYesNo.length > 0"
          v-model="queryParams.onlineFlag"
          placeholder="请选择是否线上展示"
          clearable
          filterable
          style="width: 180px"
          @change="handleOnlineFlagChange">
          <el-option v-for="d in sysYesNo" :key="d.value" :label="d.label" :value="d.value" />
        </el-select>
        <el-select v-else v-model="queryParams.onlineFlag" placeholder="加载中..." disabled style="width: 180px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:goodsinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:goodsinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goodsinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          :icon="Download"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:goodsinfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-loading="loading" 
      :data="goodsinfoList" 
      @selection-change="handleSelectionChange"
      style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="分类名称" align="center" prop="typeName" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品简介" align="center" prop="description" show-overflow-tooltip />
      <el-table-column label="首页是否推荐" align="center" prop="referrerFlag">
        <template #default="scope">
          {{ (sysYesNo.find(i => i.value === String(scope.row.referrerFlag)) || {}).label || scope.row.referrerFlag }}
        </template>
      </el-table-column>
      <el-table-column label="排序序号" align="center" prop="sortNo" />
      <el-table-column label="商品状态" align="center" prop="status">
        <template #default="scope">
          {{ (goodsStatusOptions.find(i => i.value === String(scope.row.status)) || {}).label || scope.row.status }}
        </template>
      </el-table-column>
      <el-table-column label="是否线上展示Y是N否" align="center" prop="onlineFlag">
        <template #default="scope">
          {{ (sysYesNo.find(i => i.value === String(scope.row.onlineFlag)) || {}).label || scope.row.onlineFlag }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            :icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goodsinfo:edit']"
          >修改</el-button>
          <el-button
            type="text"
            :icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goodsinfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" v-model="open" width="1200px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        
        <el-form-item label="商品分类" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择商品分类" style="width: 300px">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        
        <!-- 商品规格参数 -->
        <div style="margin-top: 10px; margin-bottom: 20px;">
          <div style="display: flex; align-items: center; margin-bottom: 8px;">
            <div style="font-weight: 600; margin-right: 20px;">商品规格参数：</div>
            <div style="display: flex; font-weight: 500; flex: 1;">
              <div style="width: 200px; margin-right: 12px;">规格</div>
              <div style="width: 160px; margin-right: 12px;">价格</div>
              <div style="width: 160px; margin-right: 12px;">库存</div>
              <div style="width: 80px;">操作</div>
            </div>
          </div>
          <!-- Data rows -->
          <div v-for="(s, idx) in form.specs" :key="idx" style="display:flex;align-items:center;margin-bottom:12px;">
            <div style="width:120px;font-weight:500;padding-right:8px;">
              <span style="color:#ff4d4f;margin-right:6px">*</span>规格{{ idx + 1 }}:
            </div>
            <el-input v-model="s.spec" placeholder="请输入商品规格" style="flex:1;margin-right:12px" />
            <el-input-number v-model="s.price" :min="0" :precision="2" style="width:160px;margin-right:12px" placeholder="价格" />
            <el-input-number v-model="s.stock" :min="0" style="width:160px;margin-right:12px" placeholder="库存" />
            <div style="width: 80px;">
              <el-button v-if="idx > 0" type="danger" plain size="small" @click="removeSpec(idx)">删除</el-button>
            </div>
          </div>
          <div style="text-align:center;margin-top:6px">
            <el-button type="text" style="color:#409EFF;" @click="addSpec">+ 添加规格参数</el-button>
          </div>
        </div>
        
        <!-- 商品简介 -->
        <el-form-item label="商品简介" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            maxlength="450"
            show-word-limit
            placeholder="请输入内容"
          />
        </el-form-item>

        <!-- 商品头图 -->
        <el-form-item label="商品头图" prop="headerImg">
          <image-upload v-model="form.headerImg" :limit="1" />
        </el-form-item>

        <!-- 详情图片 -->
        <el-form-item label="详情图片" prop="detailImg">
          <image-upload v-model="form.detailImg" :limit="5" />
        </el-form-item>
        
        <!-- 商品详情 -->
        <el-form-item label="商品详情" prop="detail">
          <Editor v-model="form.detail" :minHeight="260" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否推荐" prop="referrerFlag">
              <el-switch
                v-model="form.referrerFlag"
                active-value="Y"
                inactive-value="N"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否线上销售" prop="onlineFlag">
              <el-switch
                v-model="form.onlineFlag"
                active-value="Y"
                inactive-value="N"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sortNo">
              <el-input-number v-model="form.sortNo" :min="0" style="width: 100%" placeholder="请输入排序" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio-button v-for="s in goodsStatusOptions" :key="s.value" :value="s.value">
                  {{ s.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Goodsinfo">
import { ref, reactive, toRefs } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Download, UploadFilled } from '@element-plus/icons-vue'
import { listGoodsinfo, getGoodsinfo, delGoodsinfo, addGoodsinfo, updateGoodsinfo, exportGoodsinfo, getGoodsStatus } from "@/api/system/goodsinfo";
import { getsysYesNo, listGoodType } from '@/api/system/goodType'
import { parseTime } from '@/utils/ruoyi'
import { download } from '@/utils/request'
import { formatDate } from '@/utils/index'

const queryFormRef = ref()
const formRef = ref()
const sysYesNo = ref([])
const goodsStatusOptions = ref([])
const state = reactive({
  // 遮罩层
  loading: true,
  // 导出遮罩层
  exportLoading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 商品表格数据
  goodsinfoList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    typeName: null,
    name: null,
    description: null,
    referrerFlag: null,
    sortNo: null,
    status: null,
    onlineFlag: null
  },
  // 表单参数
  form: {
    id: null,
    typeId: null,
    typeName: null,
    name: null,
    description: null,
    headerImg: null,
    detailImg: null,
    detail: null,
    referrerFlag: 'N',
    sharePercent: null,
    sortNo: 0,
    status: "1",
    onlineFlag: 'Y',
    rebateType: 'percentage',
    level1Commission: null,
    level2Commission: null,
    level3Commission: null,
    level4Commission: null,
    unit: '',
    weight: null,
    volume: null,
    barcode: '',
    productCode: '',
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null,
    specs: []
  },
  // 表单校验
  rules: {
    name: [
      { required: true, message: "商品名称不能为空", trigger: "blur" },
      { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    status: [
      { required: true, message: "请选择商品状态", trigger: "change" }
    ],
    typeId: [
      { required: true, message: "请选择商品分类", trigger: "change" }
    ],
    sortNo: [
      { required: true, message: "请输入排序", trigger: "blur" },
      { type: 'number', min: 0, message: '排序必须为数字', trigger: 'blur' }
    ],
    unit: [
      { max: 20, message: '单位长度不能超过20个字符', trigger: 'blur' }
    ],
    weight: [
      { type: 'number', min: 0, message: '重量不能为负数', trigger: 'blur' }
    ],
    volume: [
      { type: 'number', min: 0, message: '体积不能为负数', trigger: 'blur' }
    ],
    barcode: [
      { max: 50, message: '条码长度不能超过50个字符', trigger: 'blur' }
    ],
    productCode: [
      { max: 50, message: '商品编码长度不能超过50个字符', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '商品简介不能为空', trigger: 'blur' },
      { max: 450, message: '商品简介不能超过450个字', trigger: 'blur' }
    ],
    detail: [
      { required: true, message: '商品详情不能为空', trigger: 'blur' }
    ],
    headerImg: [
      { required: true, message: '请上传商品头图', trigger: 'change' }
    ],
    detailImg: [
      { required: true, message: '请上传详情图片', trigger: 'change' }
    ]
  }
})

const { loading, exportLoading, showSearch, total, goodsinfoList, title, open, queryParams, form, rules, single, multiple } = toRefs(state)
const categoryOptions = ref([]) // 商品分类选项


/** 查询商品列表 */
function getList() {
  loading.value = true
  listGoodsinfo(queryParams.value).then(response => {
    goodsinfoList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: null,
    typeId: null,
    typeName: null,
    name: null,
    price: null,
    stock: 0,
    description: null,
    headerImg: null,
    detailImg: null,
    detail: null,
    referrerFlag: 'N',
    sharePercent: null,
    sortNo: 0,
    status: "1",
    onlineFlag: 'Y',
    rebateType: 'percentage',
    level1Commission: null,
    level2Commission: null,
    level3Commission: null,
    level4Commission: null,
    unit: '',
    weight: null,
    volume: null,
    barcode: '',
    productCode: '',
    specs: [{ id: null, spec: '', price: 0, stock: 0 }], // 默认添加一个空的规格
    createTime: null,
    createBy: null,
    updateTime: null,
    updateBy: null
  }
  formRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 商品状态选择变化处理 */
function handleStatusChange(value) {
  if (value !== null && value !== undefined && typeof value !== 'string') {
    queryParams.value.status = String(value)
  } else if (value === null || value === undefined) {
    queryParams.value.status = undefined
  }
}

/** 首页是否推荐选择变化处理 */
function handleReferrerChange(value) {
  if (value !== null && value !== undefined && typeof value !== 'string') {
    queryParams.value.referrerFlag = String(value)
  } else if (value === null || value === undefined) {
    queryParams.value.referrerFlag = undefined
  }
}

/** 是否线上展示选择变化处理 */
function handleOnlineFlagChange(value) {
  if (value !== null && value !== undefined && typeof value !== 'string') {
    queryParams.value.onlineFlag = String(value)
  } else if (value === null || value === undefined) {
    queryParams.value.onlineFlag = undefined
  }
}

// 多选框选中数据
function handleSelectionChange(selection) {
  state.ids = selection.map(item => item.id)
  state.single = selection.length!==1
  state.multiple = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加商品"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || state.ids[0]
  getGoodsinfo(id).then(response => {
    const d = response?.data || {}
    // 基本字段直接合并
    form.value = { ...form.value, ...d }

    // 后端 goodsSku -> 前端 specs 映射
    const skuList = Array.isArray(d.goodsSku) ? d.goodsSku : []
    if (skuList.length > 0) {
      form.value.specs = skuList.map(sku => ({
        id: sku.id ?? null,
        spec: sku.skuName || '',
        price: sku.price != null ? Number(sku.price) : 0,
        stock: sku.stockNum != null ? Number(sku.stockNum) : 0
      }))
    } else {
      form.value.specs = [{ id: null, spec: '', price: 0, stock: 0 }]
    }

    // 字典/开关字段统一转成字符串
    form.value.typeId = d.typeId != null ? String(d.typeId) : null
    form.value.status = d.status != null ? String(d.status) : null
    form.value.referrerFlag = d.referrerFlag != null ? String(d.referrerFlag) : null
    form.value.onlineFlag = d.onlineFlag != null ? String(d.onlineFlag) : null
    open.value = true
    title.value = "修改商品"
  })
}

/** 提交按钮 */
function submitForm() {
  formRef.value?.validate(valid => {
    if (valid) {
      // basic validation for specs: each spec must have a spec name
      const badSpec = (form.value.specs || []).findIndex(s => !s || !s.spec || String(s.spec).trim() === '')
      if (badSpec !== -1) {
        ElMessage.error(`第 ${badSpec + 1} 行规格参数名称不能为空`)
        return
      }

      // 前端 specs -> 后端 goodsSku 映射
      const specs = form.value.specs || []
      const goodsSku = specs.map((s, idx) => ({
        id: s.id ?? null,
        skuName: s.spec || String(idx + 1),
        price: s.price != null ? String(s.price) : '0',
        stockNum: s.stock != null ? String(s.stock) : '0'
      }))

      // 根据当前选中的分类ID补全分类名称，保证新增和编辑都带上正确的 typeName
      const category = categoryOptions.value.find(c => String(c.id) === String(form.value.typeId))
      const typeName = category ? category.name : form.value.typeName

      const formData = { ...form.value, typeName, goodsSku }
      if (form.value.id != null) {
        updateGoodsinfo(formData).then(response => {
          ElMessage.success("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGoodsinfo(formData).then(response => {
          ElMessage.success("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || state.ids
  ElMessageBox.confirm('是否确认删除商品编号为"' + ids + '"的数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    return delGoodsinfo(ids)
  }).then(() => {
    getList()
    ElMessage.success("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  const queryParams = { ...state.queryParams }
  ElMessageBox.confirm('是否确认导出所有项目管理数据项?', "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    state.exportLoading = true
    const { pageNum, pageSize, ...filters } = queryParams
    return download('/goods/goodsinfo/export', filters, `项目管理_${formatDate(new Date())}.xlsx`)
  }).finally(() => {
    state.exportLoading = false
  })
}

// 加载字典并再拉取列表
function loadDicts() {
  return Promise.all([
    getsysYesNo(),
    getGoodsStatus()
  ]).then(([yesNoRes, statusRes]) => {
    const yesNoArr = yesNoRes?.data || []
    sysYesNo.value = yesNoArr.map(p => ({ label: p.dictLabel, value: String(p.dictValue) }))
    const statusArr = statusRes?.data || []
    goodsStatusOptions.value = statusArr.map(p => ({ label: p.dictLabel, value: String(p.dictValue) }))
  }).catch(() => {
    sysYesNo.value = []
    goodsStatusOptions.value = []
  })
}

// 加载商品分类
const loadCategories = async () => {
  try {
    // 使用商品类型列表接口加载分类数据，对应 goods/type/list
    const res = await listGoodType({
      pageNum: 1,
      pageSize: 1000,
      status: 'Y' // 只取启用(Y)的分类
    })
    const rows = res?.rows || []
    categoryOptions.value = rows.map(item => ({
      id: item.id,
      name: item.typeName
    }))
  } catch (error) {
    console.error('加载分类失败', error)
    categoryOptions.value = []
  }
}

// 图片上传处理（商品头图 / 详情图片共用）
const handleImageChange = (file, field) => {
  const raw = file.raw || file
  const isImage = raw.type && raw.type.indexOf('image/') === 0
  const isLt5M = raw.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  // 这里应该调用上传接口
  // uploadImage(raw).then(res => {
  //   form.value[field] = res.data.url
  // })

  // 本地预览
  const reader = new FileReader()
  reader.readAsDataURL(raw)
  reader.onload = () => {
    if (field && form.value) {
      form.value[field] = reader.result
    }
  }
  return false
}

// 规格参数操作
function addSpec() {
  if (!form.value.specs) form.value.specs = []
  form.value.specs.push({ spec: '', price: 0, stock: 0 })
}

function removeSpec(index) {
  if (!form.value.specs) return
  form.value.specs.splice(index, 1)
}

// 初始化加载
onMounted(() => {
  loadDicts()
  loadCategories()
  getList()
})
</script>

<style scoped>
.form-item-hint {
  font-size: 12px;
  color: #999;
  line-height: 1.5;
  margin-top: 4px;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
}

.el-radio-group {
  width: 100%;
}

.el-radio-button {
  flex: 1;
  text-align: center;
}

.el-radio-button :deep(.el-radio-button__inner) {
  width: 100%;
}
</style>